package models

import (
	"gitchina/kly_service/data"
	"gitchina/kly_service/errors"
	"gitchina/kly_service/util"
)

type UpdateCargoOwnerRQ struct {
	CorpName      string `json:"corp_name"`
	CorpAddr      string `json:"corp_addr"`
	CorpTelephone string `json:"telephone"`
	IsCorp        bool   `json:"is_corp"`
}
type CargoOwnerRS struct {
	Name          string `json:"name"`
	IsCorp        bool   `json:"is_corp"`
	Phone         string `json:"-"`
	CorpName      string `json:"corp_name"`
	CorpAddr      string `json:"corp_addr"`
	Telpehone     string `json:"telephone"`
	BizLicenseUrl string `json:"biz_license"`
}

func (m Member) UpdateCargoOwner(mbrId ID, rq UpdateCargoOwnerRQ) (err error) {
	var id int64
	var repo data.MemberRepo
	_, _, _, id, err = mbrId.Decode()
	if err != nil {
		util.GetLogger().Error("[model - UpdateCargoOwner] - error. unexpected mbrId:%s", string(mbrId))
		err = errors.New(errors.MSG_Mbr_Invalid)
	} else {
		rq.IsCorp = true //default enti cargo owner
		err = repo.UpdateCargoOwner(&data.CargoOwnerDto{
			Id:            int(id),
			IsCorp:        rq.IsCorp,
			CorpName:      rq.CorpName,
			CorpTelephone: rq.CorpTelephone,
			CorpAddr:      rq.CorpAddr,
		})
		if err != nil {
			util.GetLogger().Error("[model - UpdateCargoOwner] - error: %s", err.Error())
		}
	}
	return err
}

func (m Member) GetCargoOwner(mbrId ID) (rs CargoOwnerRS, err error) {
	var id int64
	_, _, _, id, err = mbrId.Decode()
	if err != nil {
		util.GetLogger().Error("[model-GetCargoOwner] - unexpected mbrId:%s", string(mbrId))
		err = errors.New(errors.MSG_Mbr_Invalid)
	} else {
		var repo data.MemberRepo
		if dto, err := repo.GetCargoOwner(int(id)); err == nil {
			rs = CargoOwnerRS{
				Name:          dto.Name,
				IsCorp:        dto.IsCorp,
				Phone:         dto.Phone,
				CorpName:      dto.CorpName,
				CorpAddr:      dto.CorpAddr,
				Telpehone:     dto.Telpehone,
				BizLicenseUrl: dto.BizLicenseUrl,
			}
		} else {
			util.GetLogger().Error("[model-GetCargoOwner] - error: %s", err.Error())
			err = nil
		}
	}

	return
}
